package com.example.ercmssystem2.repository;

import com.example.ercmssystem2.entity.Resource;
import com.example.ercmssystem2.entity.ResourceType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface ResourceRepository extends JpaRepository<Resource, Long> {

    // 根据部门ID查找资源
    List<Resource> findByDepartmentIdAndStatusNot(Long departmentId, String status);

    // 根据部门ID查找所有资源
    List<Resource> findByDepartmentId(Long departmentId);

    // 根据状态查找资源
    List<Resource> findByStatus(String status);

    // 根据资源类型查找资源
    List<Resource> findByResourceType(ResourceType resourceType);

    // 根据部门ID和状态查找资源
    List<Resource> findByDepartmentIdAndStatus(Long departmentId, String status);

    // 根据资源类型和状态查找资源
    List<Resource> findByResourceTypeAndStatus(ResourceType resourceType, String status);

    // 根据名称查找资源
    Optional<Resource> findByName(String name);

    // 检查资源名称是否存在（排除指定ID）
    @Query("SELECT COUNT(r) > 0 FROM Resource r WHERE r.name = :name AND r.id != :excludeId")
    boolean existsByNameAndIdNot(@Param("name") String name, @Param("excludeId") Long excludeId);

    // 根据部门ID查找可用资源
    @Query("SELECT r FROM Resource r WHERE r.departmentId = :departmentId AND r.status = 'AVAILABLE'")
    List<Resource> findAvailableResourcesByDepartment(@Param("departmentId") Long departmentId);

    // 根据用户所在部门查找资源
    @Query("SELECT r FROM Resource r WHERE r.departmentId IN " +
           "(SELECT d.id FROM Department d WHERE d.managerId = :userId OR d.id IN " +
           "(SELECT d2.id FROM Department d2 WHERE d2.parentId IN " +
           "(SELECT d3.id FROM Department d3 WHERE d3.managerId = :userId)))")
    List<Resource> findResourcesByUserDepartments(@Param("userId") Long userId);

    // 查找所有可用资源
    List<Resource> findByStatusOrderByNameAsc(String status);
} 